class Solution
{
public:
    int surfaceArea(vector<vector<int>> &grid)
    {
        int n = grid.size();
        int result = 0;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                int height = grid[i][j];

                if (i == 0)
                {
                    result += height;
                }
                else if (height > grid[i - 1][j])
                {
                    result += height - grid[i - 1][j];
                }

                if (j == 0)
                {
                    result += height;
                }
                else if (height > grid[i][j - 1])
                {
                    result += height - grid[i][j - 1];
                }

                if (i == n - 1)
                {
                    result += height;
                }
                else if (height > grid[i + 1][j])
                {
                    result += height - grid[i + 1][j];
                }

                if (j == n - 1)
                {
                    result += height;
                }
                else if (height > grid[i][j + 1])
                {
                    result += height - grid[i][j + 1];
                }

                if (height != 0)
                {
                    result += 2;
                }
            }
        }
        return result;
    }
};